package graduation.dao.Impl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import graduation.dao.TeamActivityDao;
import graduation.entity.TeamActivity;
import graduation.vo.PageVO;


@Repository
public class TeamActivityDaoImpl extends HibernateDaoSupport implements TeamActivityDao{
	@Autowired  
    public void setSessionFactoryOverride(SessionFactory sessionFactory)  
    {  
        super.setSessionFactory(sessionFactory);  
    }
	
	@Resource
	private SessionFactory sessionFactory;

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * 添加活动
	 */
	@Override
	public void addTeamActivity(TeamActivity teamActivity) {
		// TODO Auto-generated method stub
		this.getSession().save(teamActivity);
	}
	/**
	 * 根据id获取
	 */
	@Override
	public TeamActivity getActivityById(String teamActivityId){
		String hql = "from TeamActivity where id = ?";
		Query query = this.getSession().createQuery(hql);
		query.setParameter(0, teamActivityId);
		return (TeamActivity) query.uniqueResult();
	}
	
	/**
	 * 根据id删除
	 */
	@Override
	public void deleteActivityById(String teamActivityId){
		String hql = "delete TeamActivity t where t.id=?";
		Query query = this.getSession().createQuery(hql);
		query.setParameter(0, teamActivityId);
		query.executeUpdate();
	}
	
	/**
	 * 根据修改
	 */
	@Override
	public TeamActivity updateActivityById(TeamActivity teamActivity){
		this.getSession().update(teamActivity);
		return teamActivity;
	}
	
	/**
	 * 获取全部的团建时间，按时间排逆序，返回list，分页
	 */
	@Override
	public PageVO getAllActivity(int page,int size){
		String hql = "from TeamActivity t order by t.date desc";
		Query query = this.getSession().createQuery(hql);
		//得到滚动集
		ScrollableResults scroll = query.scroll();
		//滚动到最后一行
		scroll.last();
		//得到总行数
		int count = scroll.getRowNumber() + 1;//总行数
		//设置分页信息
		query.setFirstResult(page - 1);
		query.setMaxResults(size);
		PageVO pageMessage = new PageVO();
		pageMessage.setList(query.list());
		pageMessage.setCountPage((count/size) + 1);
		pageMessage.setRecordsNum(count);
		return pageMessage;
		
	}

	@Override
	public void deleteActivity(TeamActivity teamActivity) {
		this.getSession().delete(teamActivity);
		
	}
}
